﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smoo.FolderMonitor.Components;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Windows.Forms;

namespace WpfMonitorUI.Code
{
    public class PluginLoader<T>
    {
        /// <summary>
        /// returns all plugins loaded in the application
        /// </summary>
        /// <returns></returns>
        public static List<T> AllPlugins()
        {
            string path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), Globals.PluginsPath); 
            return AllPlugins(path);
        }


        /// <summary>
        /// returns all plugins loaded in the application
        /// </summary>
        /// <returns></returns>
        public static List<T> AllPlugins(string pluginsPath)
        {
            // TODO: refactor to use a second app domain to load and search for plugins.
            List<T> plugins = new List<T>();
            string[] files = Directory.GetFiles(pluginsPath, "*.dll");

            foreach (var file in files)
            {
                try
                {
                    Assembly assembly = Assembly.LoadFile(file);

                    foreach (Type type in assembly.GetTypes())
                    {
                        if (!type.IsClass || type.IsNotPublic) continue;

                        Type[] interfaces = type.GetInterfaces();

                        if (interfaces.ToList().Contains(typeof(T)))
                        {
                            object obj = Activator.CreateInstance(type);
                            T t = (T)obj;
                            plugins.Add(t);
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.EventLog.WriteEntry("MonitorEngine", ex.Message);
                }
            }

            return plugins;
        }
    }
}
